function [rc] = loadsif_nonGUI(file, saveyn)

% [rc] = loadsif_nonGUI(file, saveyn)
%
% INPUT:        file        : filename w/o extension
%               saveyn      : 1 = save data
%               
% OUTPUT:       rc          : Return code (0 = success)

%
%     01 'Date and Time'                    'Fri Jul 16 01:58:57 2010'
%     02 'Software Version'                 '4.15.30003.0'            
%     03 'Temperature (C)'                  '-60'                     
%     04 'Model'                            'DU920P_BR,DD'            
%     05 'Data Type'                        'Optical Density'         
%     06 'Acquisition Mode'                 'Accumulate'              
%     07 'Trigger Mode'                     'Internal'                
%     08 'Exposure Time (secs)'             '0.00216'                 
%     09 'Accumulate Cycle Time (secs)'     '0.00216'                 
%     10 'Frequency (Hz)'                   '462.96'                  
%     11 'Number of Accumulations'          '50'                      
%     12 'Readout Mode'                     'Full Vertical Binning'   
%     13 'Vertical Shift Speed (usecs)'     '3.3'                     
%     14 'Pixel Readout Rate (MHz)'         '3'                       
%     15 'Baseline Clamp'                   'OFF'                     
%     16 'Clock Amplitude'                  'Normal'                  
%     17 'Output Amplifier'                 'Conventional'            
%     18 'Serial Number'                    '11182'                   
%     19 'Pre-Amplifier Gain'               '1'                       
%     20 'SR303i'                           ''                        
%     21 'Wavelength (nm)'                  '644.93'                  
%     22 'Grating Groove Density (l/mm)'    '150'                     
%     23 'Grating Blaze'                    '300'                     
%     24 'Filter'                           '1-no filter'             
%     25 'Input Side Slit Width (um)'       '10' 
%     99 'OriginalFileName'                 'xxxx.sif'
%
% This version of LOADSIF is based on the newest ATSIFIO.DLL provided by
% ANDOR support and is optimized for spectroscopic SIF files (e.g. produced
% by ANDOR Shamrock spectrographs).
% 
% !!!! ATSIFIO.DLL & atsifiomex.mexw32 have to be accessible !!!!
%

% THIS VERSION IS BASED ON loadsif3.m !!!!!!!!!!!!!!!!!!!!!!!

VersionNo = 'Version 1.3, 2012-04-13';

% Help if called without argument
if nargin<2,
    help loadsif_nonGUI
    return
end


% ----- Exmine Datafile properties ----- 
% rc            =   return code (0 = success)
% sizey         =   amount of data in y
% sizex         =   amount of data in x

% Return Codes (rc):
%
% ATSIF_SUCCESS             22002
% ATSIF_SIF_FORMAT_ERROR    22003
% ATSIF_NO_SIF_LOADED       22004
% ATSIF_FILE_NOT_FOUND      22005
% ATSIF_FILE_ACCESS_ERROR   22006
% ATSIF_DATA_NOT_PRESENT    22007

disp(VersionNo);

h = waitbar(100,{'Please wait...' 'gathering info...'},...
    'Name','Importing *.sif...');    % Status Bar INIT
[~, name, ext] = fileparts(file);
tf = isempty(ext);
if tf == 0
    q = errordlg({'Please give the filename without extension!', ' ',...
                'Long pathnames are OK, though.',' ',' ', ...
                ['File: ',name,' ; Ext.: ',ext]});
    uiwait(q)
    close(h)
    return
end
filename = name;

waitbar(0.1,h)
rc=atsif_setfileaccessmode(0);
rc=atsif_readfromfile([file,'.sif']);
if (rc == 22006)
    close(h)
    help loadsif_nonGUI
    return
end
if (rc == 22002)
  signal=0;
  [rc,present]=atsif_isdatasourcepresent(signal);
  if present
    [rc,no_frames]=atsif_getnumberframes(signal);
    if (no_frames > 0)
        [rc,size]=atsif_getframesize(signal);
%         [rc,left,bottom,right,top,hBin,vBin]=atsif_getsubimageinfo(signal,0)
        xaxis=0;
        [rc,pattern]=atsif_getpropertyvalue(signal,'ReadPattern');
        [rc,patternFull]=atsif_getpropertyvalue(signal,'ReadPatternFullName');
        if(pattern == '0') || (pattern == '2')
           datax = zeros(1,size);
           for i=1:size
               [rc,datax(i)]=atsif_getpixelcalibration(signal,xaxis,(i));
           end
        datax=datax';

%   ------------ READ SINGLE DATA ------------            
           if (no_frames == 1)
               datay = zeros(size,1);
               [rc,datay(:,1)]=atsif_getframe(signal,0,size);
               waitbar(0.8,h)
               
%   ------------ READ MULTIPLE DATA ------------ 
           else
               datay = zeros(size,no_frames);
               for i = 1:no_frames
                    [rc,datay(:,i)]=atsif_getframe(signal,i,size);
                    state=(((i/no_frames)*0.7)+0.1);
                    waitbar(state,h)
               end 
           end
           
        end
    end    
  end
  disp(['number of frames: ',num2str(no_frames)]);
  disp(['frames size: ',num2str(size)]);
  disp(['pattern: ',num2str(pattern)]);
  disp(['Full pattern: ',num2str(patternFull)]);
  footer = readsifheader(signal);
  % UPDATE: FOOTER is now a STRUCT constuct instead of a CHAR array:
    footer = cell2struct(footer(:,2), footer(:,1),1);
   
  waitbar(0.9,h,'Closinf SIF')
  atsif_closefile;                      % ----- CLOSE FILE ----------------
  rc = 0;
  if saveyn == 1
      waitbar(1,h,'Saving ...')
      savefile = [file,'.mat'];
      save(savefile, 'datax', 'datay', 'footer')
      disp(['Data read, converted, and saved as ',savefile,'.mat in current folder.']);
  else
      close(h)
      errordlg('Data read, converted, but not saved');
      return
  end
else
    close(h)
    switch rc
        case 22002
            ecstring='22002 ATSIF_SUCCESS';
        case 22003
            ecstring='22003 ATSIF_SIF_FORMAT_ERROR';
        case 22004
            ecstring='22004 ATSIF_NO_SIF_LOADED';
        case 22005
            ecstring='22005 ATSIF_FILE_NOT_FOUND';
        case 22006
            ecstring='22006 ATSIF_FILE_ACCESS_ERROR';
        case 22007
            ecstring='22007 ATSIF_DATA_NOT_PRESENT';
    end
    error(ecstring);
    errordlg(['Could not load file.  ERROR - ',ecstring]);
    return
end

close(h)





function header = readsifheader(source)

% Reads the header from the SIF file and writes to array HEADER.
%
% Format:   Date & Time

header = cell(21,2);
header = addtoheader(header, source, 'FormattedTime', 1);
header = addtoheader(header, source, 'SWVersionEx', 2);
header = addtoheader(header, source, 'Temperature', 3);
header = addtoheader(header, source, 'HeadModel', 4);
header = addtoheader(header, source, 'Operation', 5);
header = addtoheader(header, source, 'ModeFullName', 6);
header = addtoheader(header, source, 'TriggerSourceFullName', 7);
header = addtoheader(header, source, 'ExposureTime', 8);
header = addtoheader(header, source, 'IntegrationCycleTime', 9);
header = addtoheader(header, source, 'NumberIntegrations', 10);
header = addtoheader(header, source, 'KineticCycleTime', 11);
header = addtoheader(header, source, 'Frequency', 12);
header = addtoheader(header, source, 'NumberImages', 13);
header = addtoheader(header, source, 'ReadPatternFullName', 14);
header = addtoheader(header, source, 'VerticalShiftSpeed', 15);
header = addtoheader(header, source, 'PixelReadOutTime', 16);           % Hz?
header = addtoheader(header, source, 'BaselineClamp', 17);                   % Baseline Clamp?
header = addtoheader(header, source, 'VerticalClockAmp', 18);           % ClockAmp?
header = addtoheader(header, source, 'OutputAmplifier', 19);
header = addtoheader(header, source, 'Serial', 20);
header = addtoheader(header, source, 'PreAmplifierGain', 21);
header = addtoheader(header, source, 'FileName', 22);
% header = addtoheader(header, source, 'Wavelength', 23);        % ???
%  header = addtoheader(header, source, 'Filter', 24);
%  header = addtoheader(header, source, 'GratingBlaze', 25);
% header = addtoheader(header, source, 'Filter', 26);
% header = addtoheader(header, source, 'Slit', 27);


function [header] = addtoheader(header, source, para, i)
%adds a line to the footer array.
% footer    = footer array to add to
% para      = parameter name (string)
% i         = line in array (see above)

[rc,out]=atsif_getpropertyvalue(source,para);
if rc==22002
    header(i,1)= {para};
    header(i,2)= {out};
else
    error = ['ERROR: reading the footer aborted with code - ',num2str(rc)]
end






% --------------- SUBROUTINES FROM ANDOR  --------------- 
% v20101113

function ret=atsif_setfileaccessmode(readmode)

%AT_U32 ATSIF_SetFileAccessMode(ATSIF_ReadMode _mode)
%
%Description :	This function is used to select if the entire SIF file should be read 
%               or just the header section.  The read mode determines if the whole file 
%               or just the header information is read.
%
%Arguments	 : 0 - Read all
%              1 - Header Only
%
%Return		 : Check the help for return code meanings

ret = atsifiomex('ATSIF_SetFileAccessMode',readmode);


function ret=atsif_readfromfile(filename)

%AT_U32 ATSIF_ReadFromFile(AT_C * _sz_filename)
%
%Description :	This function is used to open a SIF file where the file name and path 
%               are contained in the character array _sz_filename.
%
%Arguments	 :  string containing the file path
%
%Return		 :  Check the help for return code meanings
%
%Note	     :  If the file is opened with an access mode of ATSIF_ReadAll then ATSIF_CloseFile 
%               must be called to free access to the file.

ret = atsifiomex('ATSIF_ReadFromFile',filename);


function [ret,present]=atsif_isdatasourcepresent(source)

%AT_U32 ATSIF_IsDataSourcePresent(ATSIF_DataSource _source, AT_32 *_i_present)
%
%Description :	This function is used to determine if a particular data source is present 
%               in the SIF file.  The data source is selected using the ATSIF_DataSource 
%               enumeration which has the following values:-
%
%               0 - Signal
%               1 - Reference
%               2 - Background
%               3 - Live
%               4 - Source 
%
%Arguments	 :  source - The enumeration for selecting the SIF file data source
%
%Return		 :  ret    - Check the help for return code meanings
%               prsent - 1 if prsent, 0 if not
%

[ret,present] = atsifiomex('ATSIF_IsDataSourcePresent', source);


function [ret,noframes]=atsif_getnumberframes(source)

%AT_U32 ATSIF_GetNumberFrames(ATSIF_DataSource _source, AT_U32 * _ui_images)
%
%
%Description :	This function is used to retrieve the number of frames in the SIF file.
%               The data source is selected using the ATSIF_DataSource 
%               enumeration which has the following values:-
%
%               0 - Signal
%               1 - Reference
%               2 - Background
%               3 - Live
%               4 - Source 
%
%Arguments	 :  source - The enumeration for selecting the SIF file data source
%
%Return		 :  ret    - Check the help for return code meanings
%               noframes - The number of frames in the SIF file
%

[ret,noframes] = atsifiomex('ATSIF_GetNumberFrames', source);


function [ret,size]=atsif_getframesize(source)

%AT_U32 ATSIF_GetFrameSize(ATSIF_DataSource _source, AT_U32 * _ui_size)
%
%
%Description :	This function is used to retrieve the number of pixels in each frame 
%               in the SIF file.  The data source is selected using the ATSIF_DataSource 
%               enumeration which has the following values:-
%
%               0 - Signal
%               1 - Reference
%               2 - Background
%               3 - Live
%               4 - Source 
%
%Arguments	 :  source - The enumeration for selecting the SIF file data source
%
%Return		 :  ret    - Check the help for return code meanings
%               size   - The number of pixels in each frame in the SIF file
%

[ret,size] = atsifiomex('ATSIF_GetFrameSize', source);


function [ret,propVal]=atsif_getpropertyvalue(source, propName)

%AT_U32 ATSIF_GetPropertyValue(ATSIF_DataSource _source, const AT_C * _sz_propertyName,
%                              AT_C * _sz_propertyValue, AT_U32 _ui_bufferSize)
%
%
%Description :	This function is used to retrieve image information from the SIF file.
%               The data source is selected using the ATSIF_DataSource 
%               enumeration which has the following values:-
%
%               0 - Signal
%               1 - Reference
%               2 - Background
%               3 - Live
%               4 - Source 
%
%Arguments	 :  source   - The enumeration for selecting the SIF file data source
%               propName - The selected property chosen from the list of property types
%
%               Available Properties:
%
%                 'Type'   'Active'   'Version'   'Time'   'FormattedTime'   'FileName'   
%                 'Temperature'   'SIDisplacement'   'TriggerLevel'   'Operation'  
%                 'UnstabalizedTemperature'   'Head'   'HeadModel'   'StoreType'   'DataType'   
%                 'SINumberSubFrames'   'PixelReadOutTime'   'TrackHeight'   'ReadPattern'
%                 'ReadPatternFullName'   'ShutterDelay'   'CentreRow'   'RowOffset'   
%                 'Mode'   'ModeFullName'   'TriggerSource'   'TriggerSourceFullName'   
%                 'ExposureTime'   'Delay'   'IntegrationCycleTime'   'NumberIntegrations'
%                 'KineticCycleTime'   'FlipX'   'FlipY'   'Clock'   'AClock'   'IOC'   'Frequency'
%                 'NumberPulses'   'FrameTransferAcquisitionMode'   'BaselineClamp'
%                 'PreScan'   'EMRealGain'   'BaselineOffset'   'SWVersion'   'SWVersionEx'
%                 'MCP'   'Gain'   'VerticalClockAmp'   'VerticalShiftSpeed'   'OutputAmplifier'
%                 'PreAmplifierGain'   'Serial'   'DetectorFormatX'   'DetectorFormatZ'
%                 'NumberImages'   'NumberSubImages'   'SubImageHBin'   'SubImageVBin'
%                 'SubImageLeft'   'SubImageRight'   'SubImageTop'   'SubImageBottom'
%                 'Baseline'   'CCDLeft'   'CCDRight'   'CCDTop'   'CCDBottom'   'Sensitivity'
%                 'DetectionWavelength'   'CountConvertMode''IsCountConvert'
%                 'XAxisType'   'XAxisUnit'   'YAxisType'   'YAxisUnit'   'ZAxisType'   'ZAxisUnit'
%                 'UserText'   'IsPhotonCountingEnabled'   'NumberThresholds'   'Threshold1'
%                 'Threshold2'   'Threshold3'   'Threshold4'   'AveragingFilterMode'
%                 'AveragingFactor'   'FrameCount'   'NoiseFilter'   'Threshold'
%                 'TimeStamp'
%                  To retrieve the time stamp information create the property name like so:
%                   'TimeStamp 0' will return the first frame time stamp (0 based index)
%                   'TimeStamp n-1' will return the nth frame time stamp
%
%Return		 :  ret      - Check the help for return code meanings
%               propVal -  The value of the property
%

[ret,propVal] = atsifiomex('ATSIF_GetPropertyValue', source, propName);


function [ret,data]=atsif_getframe(source, index, size)

%AT_U32 ATSIF_GetFrame(ATSIF_DataSource _source, AT_U32 _ui_index, float * _pf_data, AT_U32 _ui_bufferSize)
%
%
%Description :	This function is used to retrieve a single frame in the SIF file.
%               The data source is selected using the ATSIF_DataSource 
%               enumeration which has the following values:-
%
%               0 - Signal
%               1 - Reference
%               2 - Background
%               3 - Live
%               4 - Source 
%
%Arguments	 :  source - The enumeration for selecting the SIF file data source
%               index  - The index of the frame to retrieve
%               size   - The number of pixels in the float array
%
%Return		 :  ret    - Check the help for return code meanings
%               data   - The array of float data containing all frames in the SIF file
%

[ret,data] = atsifiomex('ATSIF_GetFrame', source, index, size);


function [ret,calVal]=atsif_getpixelcalibration(source, axis, pixel)

%AT_U32 ATSIF_GetPixelCalibration (ATSIF_DataSource _source, ATSIF_CalibrationAxis _axis,
%                                  AT_32 _i_pixel, double * _d_calibValue)
%
%
%Description :	This function is used to retrieve the calibrated value (e.g. wavelength) 
%               for the corresponding pixel in the source data of the SIF file.
%               The data source is selected using the ATSIF_DataSource 
%               enumeration which has the following values:-
%
%               0 - Signal
%               1 - Reference
%               2 - Background
%               3 - Live
%               4 - Source 
%               
%               The axis is selected using the ATSIF_CalibrationAxis enumeration, which
%               has the follwoing values:-
%
%               0 - X-Axis
%               1 - Y-Axis
%               2 - Z-Axis
%
%Arguments	 :  source   - The enumeration for selecting the SIF file data source
%               axis     - The enumeration for selecting the axis value
%               pixel    - The pixel to interrogate
%
%Return		 :  ret      - Check the help for return code meanings
%               calVal   - The corresponding pixel calibration
%

[ret,calVal] = atsifiomex('ATSIF_GetPixelCalibration', source, axis, pixel);


function [ret,data]=atsif_getallframes(source, size)

%AT_U32 ATSIF_GetAllFrames(ATSIF_DataSource _source, float * _pf_data, AT_U32 _ui_bufferSize)
%
%
%Description :	This function is used to retrieve all the frames of data in the SIF file.
%               The data source is selected using the ATSIF_DataSource 
%               enumeration which has the following values:-
%
%               0 - Signal
%               1 - Reference
%               2 - Background
%               3 - Live
%               4 - Source 
%
%Arguments	 :  source - The enumeration for selecting the SIF file data source
%               size   - The number of pixels in the float array
%
%Return		 :  ret    - Check the help for return code meanings
%               data   - The array of float data containing all frames in the SIF file
%

[ret,data] = atsifiomex('ATSIF_GetAllFrames', source, size);


function ret=atsif_closefile()

%AT_U32 ATSIF_CloseFile()
%
%Description :	This function is used to close the currently opened  SIF file.  
%               This should be called whenever the SIF has been opened using the 
%               ATSIF_ReadAll enumeration and is no longer needed by the calling program. 
%
%Arguments	 :  NONE
%
%Return		 :  Check the help for return code meanings
%

ret = atsifiomex('ATSIF_CloseFile');
